package com.springboot.fram.core.encryption;

import java.security.DigestException;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

public class Sha1 {

    /**
     * SHA1 安全加密算法
     *
     * @param decrypt 参数key-value map集合
     * @return
     * @throws DigestException 转义符参与计算
     */
    public static String sha1(String decrypt) throws Exception {
        //指定sha1算法
        MessageDigest digest = MessageDigest.getInstance("SHA1");
        digest.update(decrypt.getBytes("utf-8"));
        //获取字节数组
        byte[] messageDigest = digest.digest();
        // Create Hex String
        StringBuffer hexString = new StringBuffer();
        // 字节数组转换为 十六进制 数
        for (int i = 0; i < messageDigest.length; i++) {
            String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexString.append(0);
            }
            hexString.append(shaHex);
        }
        //将所有字母转为大写
        return hexString.toString();

    }

    /**
     * 创建签名SHA1
     *
     * @param signParams 签名参数
     * @return
     * @throws Exception
     */
    public static String sha1Sign(SortedMap<String, String> signParams) throws Exception {
        StringBuffer sb = new StringBuffer();
        Set es = signParams.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry) it.next();
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            sb.append(k + "=" + v + "&");
            //要采用URLENCODER的原始值！
        }
        String params = sb.substring(0, sb.lastIndexOf("&"));
        return sha1(params);
    }

}
